package com.project.restaurant.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * 实例化该bean时，会检测该bean是否为ApplicationContextAware,
 * 是则会((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
 */
@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    private SpringUtil(){
    }

    /**
     * 获取当前请求的session
     * @return
     */
    public static HttpSession getHttpSession() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request.getSession();
    }


    /**
     * spring一启动就会扫描所有组件注解，并将其加载进ApplicationContext上下文中。
     * @param applicationContext 传入的上下文
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(context == null){
            context = applicationContext;
        }
    }

    /**
     * 根据beanName，来获取容器里的bean
     * @param name
     * @return
     */
    public static Object getBean(String name){
        return context.getBean(name);
    }

    /**
     * 根据Class类型,来获取容器里的bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        return context.getBean(clazz);
    }
}
